<?php
/**
 * 展会分配管理
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 14:18
 */

namespace app\api\controller\activemanage;
use app\api\controller\common\ApiBase;
use app\api\model\Admin as AdminModel;
use Think\Db;


class Distribution extends ApiBase
{
    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('Exhibition');
    }

    /**
     * 展会列表
     * @return \think\response\Json|void
     */
    public function getList(){
        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page');
        $project_id = $this->request->param('project_id');
        $isShowExpire = $this->request->param('is_show_expire');
        $startTime=$this->request->param('start_time');
        $endTime=$this->request->param('end_time');

        $page = max(1,intval($page));
        $pagesize = empty(input('pageSize'))?10:input('pageSize');

        $where['is_delete'] = 0;
        if(!empty($keyword)){
            $where['title|title_en|title_as'] = array('like','%'.$keyword.'%');
        }
        if(!empty($project_id)){
            $where['project_id'] = $project_id;
        }
        if($isShowExpire==0||$isShowExpire==''){
            $where['endtime'] = array('EGT',date('Y-m-d',time()));
        }
        if(!empty($startTime)&&!empty($endTime)){
            $where['starttime'] = array('egt',$startTime);
            $where['endtime'] = array('elt',$endTime);
        }
        $list = db('exhibition')
        ->where($where)
        ->order('id desc')
        ->limit(($page-1)*$pagesize.','.$pagesize)
        ->select();
        $total = db('exhibition')
        ->where($where)
        ->count();
        if(!empty($list)){
            foreach ($list as &$v){
                $w['id'] = array('in', $v['persons']);
                $v['person_list'] = db('admin')->where($w)->select();
            }
            unset($v);
        }
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    /**
     * 条件查询展会
     */
    public function getListByCon(){
        $keyword = $this->request->param('keyword');
        $project_id = $this->request->param('project_id');

        $page = $this->request->param('page');

        $page = max(1,intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0;
        if(!empty($keyword)){
            $where['title|title_en|title_as'] = array('like','%'.$keyword.'%');
        }

        if(!empty($project_id)){
            $where['project_id'] = $project_id;
        }

        $where['endtime'] = array('EGT',date('Y-m-d',time()));

        $list = $this->model->listWherePage($where,'id desc',($page-1)*$pagesize,$pagesize);
        $total = $this->model->countWhere($where);

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    /**
     * 项目列表
     */
    public function projectList(){
        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page');

        $page = max(1,intval($page));
        $pagesize = empty(input('pageSize'))?10:input('pageSize');

        $starttime = input('starttime');
        $endtime = input('endtime');

        $where['a.is_delete'] = 0;
        if(!empty($keyword)){
            $where['title|title_en'] = array('like','%'.$keyword.'%');
        }

        if(!empty($starttime)&&!empty($endtime)){
            $where['a.create_time'] = array(array('EGT',strtotime($starttime)),array('ELT',strtotime($endtime)+86400));
        }elseif(!empty($starttime)){
            $where['a.create_time'] = array('EGT',strtotime($starttime));
        }elseif(!empty($endtime)){
            $where['a.create_time'] = array('ELT',strtotime($endtime));
        }

        //$list = $this->model->listWherePage($where,'id desc',);
        $list = db('project')->alias('a')->field('a.*,b.account')->join('admin b','a.create_uid=b.id')->order('id desc')->limit(($page-1)*$pagesize.','.$pagesize)->where($where)->select();
        $total = db('project')->alias('a')->where($where)->count();

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    /**
     * 展会详情
     * @return \think\response\Json|void
     */
    public function detail(){
        $id = $this->request->param('id');

        $where['id'] = $id;
        $where['is_delete'] = 0;
        $info = $this->model->findWhere($where);

        #展会信息

        return json(['code'=>1,'msg'=>'success','data'=>$info]);
    }

    /**
     * 删除展会
     * @return \think\response\Json|void
     */
    public function del(){
        $id = $this->request->param('id');

        $where = ['id'=>['in',$id],'is_delete'=>0];
        $r = $this->model->countWhere($where);

        if(empty($r)){
            return json(['code'=>0,'msg'=>'记录不存在，请核实']);
        }

        $r = $this->model->deleteWhere(['id'=>$id]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     *
     * @return mixed
     */
   public function _before_add(){
       $data['title'] = $this->request->param('title');
       $data['title_en'] = $this->request->param('title_en');
       $data['title_as'] = $this->request->param('title_as');
       $data['project_id'] = $this->request->param('project_id');
       $data['industry_id'] = $this->request->param('industry_id');
       $data['starttime']  = $this->request->param('starttime');
       $data['endtime']  = $this->request->param('endtime');
       $data['city']  = $this->request->param('city');
       $data['category_id']  = $this->request->param('category_id');
       $data['customer_manager']  = $this->request->param('customer_manager');
       $data['questionnaire_id']  = $this->request->param('questionnaire_id');
       $data['is_company']  = $this->request->param('is_company');
       $data['merchants_manager']  = $this->request->param('merchants_manager');
       $data['merchants_group']  = $this->request->param('merchants_group');
       $data['exhibition_level']  = $this->request->param('exhibition_level');
       $data['is_exhibition']  = $this->request->param('is_exhibition');

       return $data;
   }

    /**
     * 增加展会
     * @return \think\response\Json|void
     */
    public function add(){
        $data = $this->_before_add();
        $data['create_time']  = time();
        $data['update_time']  = time();
        $data['is_delete']  = 0;

        $r = $this->model->insertData($data);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 编辑展会
     * @return \think\response\Json|void
     */
    public function edit(){
        $id = $this->request->param('id');
        $data = $this->_before_add();
        $data['update_time']  = time();

        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误，请核查']);
        }

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data,$where);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 展会分类列表
     */
    public function typeList(){
        $list = db('exhibition_type')->where('is_delete',0)->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);;
    }

    /**
     * 增加展会分类
     * @return \think\response\Json|void
     */
    public function addType(){
        $title = $this->request->param('title');
        $r = db('exhibition_type')->insertGetId(['title'=>$title]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 编辑展会分类
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editType(){
        $id = $this->request->param('id');
        $title = $this->request->param('title');
        $r = db('exhibition_type')->where('id',$id)->update(['title'=>$title]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 删除展会类型
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delType(){
        $id = $this->request->param('id');
        $r = db('exhibition_type')->where('id',$id)->update(['is_delete'=>1]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 获取当前管理员展会列表
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserExhib(){

        #判断是否是管理员
        $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
        if(!$role_id&&$this->admin['is_super']==0){
            return json(['code'=>0,'msg'=>'角色不存在']);
        }

        if($role_id){
            $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
            if(!$is_gl){
                return json(['code'=>0,'msg'=>'not_gl']);
            }
        }

        if($this->admin['is_super']==0){
            $where['merchants_manager'] = $this->admin['id'];
        }

        //$where['endtime'] = array('LT',date('Y-m-d',time()));
        $where['is_delete'] = 0;
        $data = db('exhibition')->field('title,id')->order('id desc')->where($where)->select();

        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }

    /**
     * 获取展会下所有展厅
     */
    public function getAllHall(){
        $id = input('id');
        if(empty($id)){
            return json(['code'=>1,'msg'=>'参数有误']);
        }
        $list = db('hall')->alias('a')->field('a.*')->join('pavilion b','a.pavilion_id=b.id','left')->where('b.exhibition_id',$id)->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                // $where['a.org_id'] = $orgId;
                $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    //获得分配人员的数据
    public function getPersonExh(){
        $eId = $this->request->param('eId');
        $where['id'] = $eId;
        $data = db('exhibition')->field('persons')->where($where)->select();
        if(!empty($data) && is_array($data)){
            $where['id'] = array('in', $data[0]['persons']);
            $list = db('admin')->where($where)->select();
        }
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }


    //分配人员数据跟新
    public function setPersonExh(){
        $pIds = $this->request->param('pIds');
        $id = $this->request->param('id');
        if(empty($pIds)){
            $pIds=null;
        }
        $r = db('exhibition')->where('id',$id)->update(['persons'=>$pIds]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }
}